package com.supor.aiot.home.utils;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.common.utils.Util;
import com.supor.aiot.common.base.BaseMVVMFragment;
import com.supor.aiot.common.ui.view.IndicatorPagerTitleView;
import com.supor.aiot.common.utils.AnimationUtil;
import com.supor.aiot.home.R;
import com.supor.aiot.home.ui.device.config.hw.HwConfigStateFragment;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import static androidx.fragment.app.FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: HwTouchPop <br>
 * 作者: lei <br>
 * 日期: 2021/11/4 <br>
 */
public class HwTouchPop {

    private static final String[] CHANNELS = new String[]{"华为免安装App配网", "苏泊尔App配网"};
    private List<String> mDataList = Arrays.asList(CHANNELS);
    // private ExamplePagerAdapter mExamplePagerAdapter = new ExamplePagerAdapter(mDataList);

    static PopupWindow popupWindow;
    View popWindowView;
    Handler handler;
    private WeakReference<FragmentActivity> activityReference;

    private static volatile HwTouchPop instance;
    private float alpha;
    int duration = 500;
    int sleepTime = duration / 100;
    ImageView ivClose;
    MagicIndicator indicator1;
    ImageView indicator2;
    ViewPager viewPager;

    public static HwTouchPop getInstance() {
        if (instance == null) {
            instance = new HwTouchPop();
        }
        return instance;
    }

    private HwTouchPop() {
    }

    public void initPop(FragmentActivity activity) {
        activityReference = new WeakReference<>(activity);
        handler = new Handler(activity.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    AnimationUtil.backgroundAlpha(activityReference.get(), (float) msg.obj);
                }
            }
        };
        popupWindow = new PopupWindow();
        popWindowView = LayoutInflater.from(activity).inflate(R.layout.pop_hw_touch, null);
        popupWindow.setContentView(popWindowView);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);// 解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(false);// 点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.popup_window_anim);

        ivClose = popWindowView.findViewById(R.id.iv_close);
        indicator1 = popWindowView.findViewById(R.id.magic_indicator1);
        indicator2 = popWindowView.findViewById(R.id.indicator2);
        viewPager = popWindowView.findViewById(R.id.view_pager);

        ivClose.setOnClickListener(v -> popupWindow.dismiss());
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        // 退出popupWindow时取消暗背景
        popupWindow.setOnDismissListener(() -> ThreadUtils.execute(() -> {
            while (alpha < 1f) {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                alpha += 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        }));

        initView();
    }

    private void initView() {
        ArrayList<BaseMVVMFragment> fragments = new ArrayList<>();
        fragments.add(HwConfigStateFragment.newInstance(1));
        fragments.add(HwConfigStateFragment.newInstance(2));
        viewPager.setAdapter(new FragmentPagerAdapter(activityReference.get().getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });
        viewPager.setOffscreenPageLimit(fragments.size());

        initMagicIndicator1();
    }

    private void initMagicIndicator1() {
        CommonNavigator commonNavigator = new CommonNavigator(activityReference.get());
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                IndicatorPagerTitleView pagerTitleView = new IndicatorPagerTitleView(context);
                pagerTitleView.setSelectedBold(true);
                pagerTitleView.setSelectedTextSize(Util.dip2px(activityReference.get(),
                        getSize(activityReference.get(), R.dimen.sp_12)));
                pagerTitleView.setUnselectedTextSize(Util.dip2px(activityReference.get(),
                        getSize(activityReference.get(), R.dimen.sp_12)));
                pagerTitleView.setText(mDataList.get(index));
                pagerTitleView.setNormalColor(Color.parseColor("#666666"));
                pagerTitleView.setSelectedColor(Color.parseColor("#333333"));
                pagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(index);
                    }
                });
                return pagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setRoundRadius(Util.dip2px(activityReference.get(),
                        getSize(activityReference.get(), R.dimen.dp_4)));
                indicator.setColors(Color.parseColor("#16BF86"));
                indicator.setLineWidth(Util.dip2px(activityReference.get(),
                        getSize(activityReference.get(), R.dimen.dp_83)));
                indicator.setLineHeight(Util.dip2px(activityReference.get(),
                        getSize(activityReference.get(), R.dimen.dp_6)));
                return indicator;
            }
        });

        indicator1.setNavigator(commonNavigator);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                indicator1.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                indicator1.onPageSelected(position);
                if (position == 0) {
                    indicator2.setImageResource(R.mipmap.ic_hw_dot1);
                } else {
                    indicator2.setImageResource(R.mipmap.ic_hw_dot2);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                indicator1.onPageScrollStateChanged(state);
            }
        });
        // LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
        // titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        // titleContainer.setDividerPadding(UIUtil.dip2px(activityReference.get(), 5));
        // titleContainer.setDividerDrawable(activityReference.get().getResources().getDrawable(R.drawable.simple_splitter));
        // ViewPagerHelper.bind(indicator1, viewPager);
    }

    public void showPop(FragmentActivity activity, View rootView) {
        if (popupWindow == null) {
            initPop(activity);
        } else {
            ivClose.setVisibility(View.GONE);
            ivClose.setVisibility(View.INVISIBLE);
            indicator1.setVisibility(View.VISIBLE);
            ivClose.setVisibility(View.VISIBLE);
        }
        popupWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        alpha = 1f;
        ThreadUtils.execute(() -> {
            while (alpha > 0.5f) {
                try {
                    // 根据弹出动画时间和减少的透明度计算时间
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                // 每次减少0.005，精度越高，变暗的效果越流畅
                alpha -= 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public boolean isPopShow() {
        return popupWindow != null && popupWindow.isShowing();
    }

    public void dismissPop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }
    private int getSize(Context context, int dimen) {
        return Util.px2dip(context, context.getResources().getDimensionPixelSize(dimen));
    }

    public View getPopWindow() {
        return popWindowView;
    }
}
